<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Reality | Reality</title><meta name="keywords" content="Java, 全栈"><meta name="author" content="dtyy"><meta name="copyright" content="dtyy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="文件图片上传是Web开发的基本功能。 1 文件上传业务实现@Api(value &#x3D; &quot;用户信息接口&quot;, tags &#x3D; &quot;用户信息接口&quot;) @RestController @RequestMapping(&quot;userInfo&quot;) public class CenterUserController extends BaseController {      @Autowired     private">
<meta property="og:type" content="article">
<meta property="og:title" content="Reality">
<meta property="og:url" content="https://dtyytop.gitee.io/2021/05/13/devnotes/xiang-mu-shi-jian/shang-cheng-xiang-mu/web-tou-xiang-shang-chuan-gong-neng/index.html">
<meta property="og:site_name" content="Reality">
<meta property="og:description" content="文件图片上传是Web开发的基本功能。 1 文件上传业务实现@Api(value &#x3D; &quot;用户信息接口&quot;, tags &#x3D; &quot;用户信息接口&quot;) @RestController @RequestMapping(&quot;userInfo&quot;) public class CenterUserController extends BaseController {      @Autowired     private">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg">
<meta property="article:published_time" content="2021-05-13T14:22:22.353Z">
<meta property="article:modified_time" content="2021-05-13T14:22:22.353Z">
<meta property="article:author" content="dtyy">
<meta property="article:tag" content="Java, 全栈">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://dtyytop.gitee.io/2021/05/13/devnotes/xiang-mu-shi-jian/shang-cheng-xiang-mu/web-tou-xiang-shang-chuan-gong-neng/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"prismjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: dtyy","link":"链接: ","source":"来源: Reality","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Reality',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-05-13 22:22:22'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Reality" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Reality</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">无题</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-05-13T14:22:22.353Z" title="发表于 2021-05-13 22:22:22">2021-05-13</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-05-13T14:22:22.353Z" title="更新于 2021-05-13 22:22:22">2021-05-13</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">876</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>3分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p> 文件图片上传是Web开发的基本功能。</p>
<h3 id="1-文件上传业务实现"><a href="#1-文件上传业务实现" class="headerlink" title="1 文件上传业务实现"></a>1 文件上传业务实现</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Api</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"用户信息接口"</span><span class="token punctuation">,</span> tags <span class="token operator">=</span> <span class="token string">"用户信息接口"</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@RestController</span>
<span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span><span class="token string">"userInfo"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CenterUserController</span> <span class="token keyword">extends</span> <span class="token class-name">BaseController</span> <span class="token punctuation">{</span>

    <span class="token annotation punctuation">@Autowired</span>
    <span class="token keyword">private</span> <span class="token class-name">CenterUserService</span> centerUserService<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Autowired</span>
    <span class="token keyword">private</span> <span class="token class-name">FileUpload</span> fileUpload<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@ApiOperation</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"修改用户头像"</span><span class="token punctuation">,</span> notes <span class="token operator">=</span> <span class="token string">"修改用户头像"</span><span class="token punctuation">,</span> httpMethod <span class="token operator">=</span> <span class="token string">"POST"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@PostMapping</span><span class="token punctuation">(</span><span class="token string">"/uploadFace"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">ServerResponse</span> <span class="token function">uploadFace</span><span class="token punctuation">(</span>
            <span class="token annotation punctuation">@ApiParam</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"userId"</span><span class="token punctuation">,</span> value <span class="token operator">=</span> <span class="token string">"用户id"</span><span class="token punctuation">,</span> required <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
            <span class="token annotation punctuation">@RequestParam</span> <span class="token class-name">String</span> userId<span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiParam</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"file"</span><span class="token punctuation">,</span> value <span class="token operator">=</span> <span class="token string">"用户头像"</span><span class="token punctuation">,</span> required <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
                    <span class="token class-name">MultipartFile</span> file<span class="token punctuation">,</span>
            <span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> <span class="token class-name">HttpServletResponse</span> response
    <span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token comment">// 定义头像保存地址</span>
        <span class="token class-name">String</span> fileSpace <span class="token operator">=</span> fileUpload<span class="token punctuation">.</span><span class="token function">getImageUserFaceLocation</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 上传路径，用userid标识</span>
        <span class="token class-name">String</span> uploadPath <span class="token operator">=</span> <span class="token class-name">File</span><span class="token punctuation">.</span>separator <span class="token operator">+</span> userId<span class="token punctuation">;</span>

        <span class="token comment">// 文件上传操作</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>file <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">// 获取文件名称</span>
            <span class="token class-name">String</span> fileName <span class="token operator">=</span> file<span class="token punctuation">.</span><span class="token function">getOriginalFilename</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token class-name">StringUtils</span><span class="token punctuation">.</span><span class="token function">isNoneBlank</span><span class="token punctuation">(</span>fileName<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token comment">// 重命名文件</span>
                <span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> arr <span class="token operator">=</span> fileName<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">"\\."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment">// 获取后缀名</span>
                <span class="token class-name">String</span> suffix <span class="token operator">=</span> arr<span class="token punctuation">[</span>arr<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>

                <span class="token comment">// 图片格式限制，以防止后门。黑客会直接攻击web服务器。</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>suffix<span class="token punctuation">.</span><span class="token function">equalsIgnoreCase</span><span class="token punctuation">(</span><span class="token string">"png"</span><span class="token punctuation">)</span>
                        <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span>suffix<span class="token punctuation">.</span><span class="token function">equalsIgnoreCase</span><span class="token punctuation">(</span><span class="token string">"jpg"</span><span class="token punctuation">)</span>
                        <span class="token operator">&amp;&amp;</span> <span class="token operator">!</span>suffix<span class="token punctuation">.</span><span class="token function">equalsIgnoreCase</span><span class="token punctuation">(</span><span class="token string">"jpeg"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">return</span> <span class="token class-name">ServerResponse</span><span class="token punctuation">.</span><span class="token function">createByErrorMsg</span><span class="token punctuation">(</span><span class="token string">"图片格式不正确！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>

                <span class="token comment">// 重组文件名</span>
                <span class="token class-name">String</span> newFileName <span class="token operator">=</span> <span class="token string">"face-"</span> <span class="token operator">+</span> userId <span class="token operator">+</span> <span class="token string">"."</span> <span class="token operator">+</span> suffix<span class="token punctuation">;</span>

                <span class="token comment">// 图像的最终保存位置</span>
                <span class="token class-name">String</span> finalPath <span class="token operator">=</span> fileSpace <span class="token operator">+</span> uploadPath <span class="token operator">+</span> <span class="token class-name">File</span><span class="token punctuation">.</span>separator <span class="token operator">+</span> newFileName<span class="token punctuation">;</span>
                <span class="token comment">// web访问地址</span>
                uploadPath <span class="token operator">+=</span> <span class="token punctuation">(</span><span class="token string">"/"</span> <span class="token operator">+</span> newFileName<span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token class-name">File</span> outFile <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">File</span><span class="token punctuation">(</span>finalPath<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span>outFile<span class="token punctuation">.</span><span class="token function">getParentFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token comment">// 创建文件夹</span>
                    outFile<span class="token punctuation">.</span><span class="token function">getParentFile</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">mkdirs</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
                <span class="token comment">// 文件保存到指定目录</span>
                <span class="token class-name">FileOutputStream</span> fos <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                <span class="token class-name">InputStream</span> is <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
                <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    fos <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FileOutputStream</span><span class="token punctuation">(</span>outFile<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    is <span class="token operator">=</span> file<span class="token punctuation">.</span><span class="token function">getInputStream</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token class-name">IOUtils</span><span class="token punctuation">.</span><span class="token function">copy</span><span class="token punctuation">(</span>is<span class="token punctuation">,</span> fos<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
                    <span class="token keyword">try</span> <span class="token punctuation">{</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>fos <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                            fos<span class="token punctuation">.</span><span class="token function">flush</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                            fos<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">}</span>
                        <span class="token keyword">if</span> <span class="token punctuation">(</span>is <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                            is<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">}</span>
                    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">IOException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token class-name">ServerResponse</span><span class="token punctuation">.</span><span class="token function">createByErrorMsg</span><span class="token punctuation">(</span><span class="token string">"文件不能为空"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment">// 由于浏览器可能存在缓存，所以加上时间戳保证更新后的图片可以及时更新</span>
        <span class="token class-name">String</span> finalImageServerUrl <span class="token operator">=</span>
                fileUpload<span class="token punctuation">.</span><span class="token function">getImageServerUrl</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> uploadPath <span class="token operator">+</span> <span class="token string">"?t="</span> <span class="token operator">+</span> <span class="token class-name">DateUtil</span><span class="token punctuation">.</span><span class="token function">getCurrentDateString</span><span class="token punctuation">(</span><span class="token class-name">DateUtil</span><span class="token punctuation">.</span>DATE_PATTERN<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 更新用户头像到数据库</span>
        <span class="token class-name">Users</span> user <span class="token operator">=</span> centerUserService<span class="token punctuation">.</span><span class="token function">updateFace</span><span class="token punctuation">(</span>userId<span class="token punctuation">,</span> finalImageServerUrl<span class="token punctuation">)</span><span class="token punctuation">;</span>

		<span class="token comment">// 其他业务操作</span>

        <span class="token keyword">return</span> <span class="token class-name">ServerResponse</span><span class="token punctuation">.</span><span class="token function">createBySuccess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>文件上传，后续有nginx，FastDFS以及云服务演进。</p>
<h3 id="2-读取文件路径配置"><a href="#2-读取文件路径配置" class="headerlink" title="2 读取文件路径配置"></a>2 读取文件路径配置</h3><p>file-upload-dev.properties</p>
<pre class="line-numbers language-none"><code class="language-none">file.imageUserFaceLocation=\\workspaces\\images\\emall\\faces
file.imageServerUrl=http://localhost:8088/emall/faces<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>属性读取类</p>
<pre class="line-numbers language-none"><code class="language-none">@Component // 组件注册到容器
@ConfigurationProperties(prefix = "file") // 扫描前缀
@PropertySource("classpath:file-upload-dev.properties") // 切换环境
public class FileUpload {

    /**
     * web服务器图片位置
     */
    private String imageUserFaceLocation;

    /**
     * 图像web映射地址
     */
    private String imageServerUrl;

    public String getImageServerUrl() {
        return imageServerUrl;
    }

    public void setImageServerUrl(String imageServerUrl) {
        this.imageServerUrl = imageServerUrl;
    }

    public String getImageUserFaceLocation() {
        return imageUserFaceLocation;
    }

    public void setImageUserFaceLocation(String imageUserFaceLocation) {
        this.imageUserFaceLocation = imageUserFaceLocation;
    }

}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="3-静态资源网络映射"><a href="#3-静态资源网络映射" class="headerlink" title="3 静态资源网络映射"></a>3 静态资源网络映射</h3><pre class="line-numbers language-none"><code class="language-none">@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 实现自定义静态资源映射
     * &lt;p&gt;
     * 访问：http://localhost:8088/emall/faces/2007245DMB28AKS8/face-2007245DMB28AKS8.jpg
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**") // 拦截所有静态资源
                .addResourceLocations("classpath:/META-INF/resources/") // 映射swagger2
                .addResourceLocations("file:/workspaces/images/"); // 映射本地静态资源
    }

}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="4-图片格式限制"><a href="#4-图片格式限制" class="headerlink" title="4 图片格式限制"></a>4 图片格式限制</h3><p>对于图片格式，前端是有限制的。但非法用户通常会越过前端，上传恶意脚本，直接攻击web服务器。为了系统安全性，后端对图片格式进行校验。</p>
<pre class="line-numbers language-none"><code class="language-none">// 图片格式限制，以防止后门。黑客会直接攻击web服务器。
if (!suffix.equalsIgnoreCase("png")
        &amp;&amp; !suffix.equalsIgnoreCase("jpg")
        &amp;&amp; !suffix.equalsIgnoreCase("jpeg")) {
    return ServerResponse.createByErrorMsg("图片格式不正确！");
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="5-文件大小限制"><a href="#5-文件大小限制" class="headerlink" title="5 文件大小限制"></a>5 文件大小限制</h3><p>文件大小限制，可以在application.yaml文件配置。</p>
<pre class="line-numbers language-none"><code class="language-none">spring.servlet.multipart:
    max-file-size: 200KB  # 文件上传大小限制为200KB
    max-request-size: 200KB # 请求大小限制为200KB<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>当文件超过限制，会抛如下异常。</p>
<pre class="line-numbers language-none"><code class="language-none">严重: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>



<h3 id="6-自定义捕获异常"><a href="#6-自定义捕获异常" class="headerlink" title="6 自定义捕获异常"></a>6 自定义捕获异常</h3><p>为了使错误信息更加人性化的反馈给用户，我们定义handler类</p>
<pre class="line-numbers language-none"><code class="language-none">/**
 * 自定义异常助手类
 *
 * @author dtyy
 * @date 2020/10/15
 */
@RestControllerAdvice
public class CustomExceptionHandler {

    // MaxUploadSizeExceededException
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ServerResponse handleMaxUploadFile(MaxUploadSizeExceededException exception) {
        return ServerResponse.createByErrorMsg("文件大小不能超过200KB");
    }

}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">dtyy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://dtyytop.gitee.io/2021/05/13/devnotes/xiang-mu-shi-jian/shang-cheng-xiang-mu/web-tou-xiang-shang-chuan-gong-neng/">https://dtyytop.gitee.io/2021/05/13/devnotes/xiang-mu-shi-jian/shang-cheng-xiang-mu/web-tou-xiang-shang-chuan-gong-neng/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://dtyytop.gitee.io" target="_blank">Reality</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/05/13/devnotes/xiang-mu-shi-jian/shang-cheng-xiang-mu/shi-yong-hibernate-validator-yan-zheng-ye-wu-can-shu/"><img class="prev-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info"></div></div></a></div><div class="next-post pull-right"><a href="/2021/05/13/devnotes/xiang-mu-shi-jian/shang-cheng-xiang-mu/guan-bi-chao-shi-wei-zhi-fu-ding-dan/"><img class="next-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222621.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info"></div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">dtyy</div><div class="author-info__description">Java全栈</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/dtyytop"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/dtyytop" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1607961042@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%9A%E5%8A%A1%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.</span> <span class="toc-text">1 文件上传业务实现</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84%E9%85%8D%E7%BD%AE"><span class="toc-number">2.</span> <span class="toc-text">2 读取文件路径配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E7%BD%91%E7%BB%9C%E6%98%A0%E5%B0%84"><span class="toc-number">3.</span> <span class="toc-text">3 静态资源网络映射</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E5%9B%BE%E7%89%87%E6%A0%BC%E5%BC%8F%E9%99%90%E5%88%B6"><span class="toc-number">4.</span> <span class="toc-text">4 图片格式限制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-%E6%96%87%E4%BB%B6%E5%A4%A7%E5%B0%8F%E9%99%90%E5%88%B6"><span class="toc-number">5.</span> <span class="toc-text">5 文件大小限制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#6-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8D%95%E8%8E%B7%E5%BC%82%E5%B8%B8"><span class="toc-number">6.</span> <span class="toc-text">6 自定义捕获异常</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx进程模型"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型">Nginx进程模型</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx核心配置结构"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构">Nginx核心配置结构</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="集群、代理与Nginx"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx">集群、代理与Nginx</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222646.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis主从复制架构与原理"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理">Redis主从复制架构与原理</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis的两种持久化机制"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制">Redis的两种持久化机制</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222627.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By dtyy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>